<template>
  <div class="el-page-header" @keydown.enter="handleLogin">
    <ParticlesView></ParticlesView>
    <div style="margin-left: 20px;margin-top: 10px;font-size: 20px;color: #fcfcfc;font-weight: bold">
      <span>药品用法用量查询系统
<!--        <el-statistic-->
<!--          ref="statistic"-->
<!--          @finish="hilarity"-->
<!--          format="HH:mm:ss"-->
<!--          :value="deadline4"-->
<!--          title="距离明日："-->
<!--          time-indices-->
<!--        >-->
<!--      </el-statistic>-->

      </span>
      <p>{{deadline4}}</p>
    </div>
    <div class="meituan-content">
      <div class="images-layout"></div>
      <div class="common-layout" :class="{ 'loading': loginLoading }">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px" status-icon class="demo-ruleForm">
          <el-form-item label="" prop="username">
            <el-input type="username" v-model="form.username" placeholder="请输入账户">
              <i class="el-icon-user" slot="prefix" style="color: black"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="" prop="password">
            <el-input type="password" placeholder="请输入密码" v-model="form.password" show-password>
              <i class="el-icon-lock" slot="prefix" style="color: black"></i>
            </el-input>
          </el-form-item>
          <div class="check-code-panel">
            <el-form-item label="" prop="verificationCode">
              <el-input type="verificationCode" v-model="form.verificationCode" placeholder="请输入验证码">
                <i class="el-icon-position" slot="prefix" style="color: black"></i>
              </el-input>
<!--              <img id="captchaImage" :src="captchaImageUrl" @click="refreshCaptcha" style="width: 98px;height: 40px"/>-->
              <img id="captchaImage" :src="getImage()" @click="refreshCaptcha" style="width: 88px; height: 38px; position: absolute; right: 1px; top: 50%; transform: translateY(-50%); cursor: pointer;">
            </el-form-item>
          </div>
          <el-form-item style="padding-top: 1px">
            <el-button type="primary" @click="handleLogin" class="login" :loading="loginLoading">登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import newLogo from '@/assets/images/yao.jpg'
import background from '@/assets/images/zhongyao2.png'
import { login } from '@/api/login'
import { mapActions, mapMutations } from 'vuex'
import ParticlesView from '../../components/particles/ParticlesView'
import CryptoJS from 'crypto-js'
import axios from 'axios'
// import handleAxiosError from '@/api/error'
export default {
  components: {
    ParticlesView
  },
  data () {
    return {
      form: {
        username: 'admin',
        password: '12345678',
        // rememberMe: false,
        verificationCode: '',
        publicIp: '',
        hostName: navigator.userAgent
      },
      // deadline4: Date.now() + (new Date().setHours(23, 59, 59) - Date.now()),
      deadline4: '',
      newLogo,
      background,
      captchaBaseUrl: '',
      captchaImageApi: '/user/code',
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        verificationCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      loginLoading: false,
      showAnimation: false,
      imageCode: ''
    }
  },
  created () {
    // 将服务端地址挂载到全局
    this.captchaBaseUrl = this.$requestcode.defaults.baseURL
  },
  mounted () {
    this.getPublicIp()
    this.getNowTime()
    // this.getImage()
    // alert(this.form.hostName)
  },
  methods: {
    getNowTime () {
      setInterval(() => {
        this.deadline4 = new Date().toLocaleDateString() + '  ' + new Date().toLocaleTimeString()
      })
    },
    getPublicIp () {
      axios.get('https://api.ipify.org?format=json')
        .then(resp => {
          this.form.publicIp = resp.data.ip
        })
        .catch(error => {
          this.handleAxiosError(error)
        })
    },
    hilarity () {
      this.$notify({
        title: '提示',
        message: '时间已到',
        duration: 0
      })
    },
    getImage () {
      return this.captchaBaseUrl + this.captchaImageApi + '?'
    },
    refreshCaptcha () {
      this.captchaImageApi = '/user/code?' + new Date().getTime()
      // axios.get('http://localhost:8888/api/user/verificationCode').then((res) => {
      //   console.log(res.data.data)
      //   this.imageCode = res.data.data
      // }).catch(error => {
      //   this.handleAxiosError(error)
      // })
    },
    myError (error) {
      if (error.isAxiosError) {
        this.$message({
          message: '错误',
          type: 'error',
          duration: 0
        })
      } else {
        this.$message({
          message: '错误',
          type: 'error',
          duration: 0
        })
      }
    },
    open1 () {
      this.$notify({
        title: '自定义位置',
        message: '右上角弹出的消息'
      })
    },
    ...mapMutations('menu', ['setUserId', 'setToken']),
    ...mapActions('menu', ['setUserInfo']),
    handleLogin () {
      this.loginLoading = true
      // const hash = this.hashPassword(this.form.password)
      // alert(hash)
      // 构造请求参数
      const requestData = {
        username: this.form.username,
        password: this.form.password,
        verificationCode: this.form.verificationCode,
        publicIp: this.form.publicIp,
        hostName: this.form.hostName
      }
      // 调用登录函数发起请求
      this.$refs.form.validate((valid) => {
        if (valid) {
          login(requestData).then((resp) => {
            if (resp.data.flag === true) {
              this.loginLoading = false
              this.$message({
                type: 'success',
                message: resp.data.message,
                center: true,
                offset: 100
              })
              // this.setRememberMeCookie(resp.data)
              localStorage.setItem('userId', JSON.stringify(resp.data.data.id))
              localStorage.setItem('username', JSON.stringify(resp.data.data.username))
              localStorage.setItem('token', resp.data.token)
              this.setUserInfo({
                userId: JSON.stringify(resp.data.data.id),
                username: resp.data.data.username,
                token: resp.data.token
              })
              // alert(resp.data.token)
              this.$router.replace('/backend.html')
            } else {
              this.loginLoading = false
              this.refreshCaptcha()
              this.$message({
                type: 'error',
                message: resp.data.message,
                center: true,
                offset: 100
              })
            }
          }).catch((error) => {
            this.handleAxiosError(error)
          })
        } else {
          this.loginLoading = false
          // this.$message({
          //   type: 'error',
          //   message: '请输入相关内容！！！',
          //   center: true
          // })
          this.$notify({
            type: 'error',
            title: '登录错误',
            message: '请输入完整信息！！！',
            position: 'top-left',
            offset: 50
          })
          this.refreshCaptcha()
        }
      })
    },
    setRememberMeCookie (userData) {
      this.$cookies.set('rememberMe', userData, '1m')// '7d' 天
    },
    handleEnterKey () {
      this.handleLogin()
    },
    hashPassword (password) {
      const salt = this.generateSalt()
      return CryptoJS.SHA256(password + salt).toString()
    },
    generateSalt () {
      // 生成一个随机的十六进制字符串作为盐值
      return CryptoJS.lib.WordArray.random(128 / 8).toString()
    },
    handleAxiosError (error) {
      // 检查是否是Axios的网络错误
      if (error.isAxiosError || error.response || error.request) {
        // 处理您的网络错误，例如显示用户友好的提示
        this.$message({
          type: 'error',
          message: '网络请求失败，请稍后重试',
          center: true,
          offset: 100
        })
        this.loginLoading = false
      } else {
        // 处理其他类型的错误
        this.$message({
          type: 'error',
          message: '网络请求失败，发生错误，请稍后重试',
          center: true,
          offset: 100
        })
        this.loginLoading = false
      }
    }
  }
}

</script>

<style scoped>
/*@import '../../assets/css/login.css';*/
.el-page-header {
  /*渐变*/
  /*background: url("../../assets/login-back.jpg") no-repeat;*/
  background: linear-gradient(to left, #ec032e, #14ade5);
  z-index: 1;
  position: fixed;
  width: 100%;
  height: 100%;
  background-size: cover;
  top: 0;
  left: 0;
}
.meituan-content {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  height: 315px;
  border-radius: 12px;
  background-color: #fcfcfc;
  /*渐变背景色*/
  /*background: linear-gradient(to right, #ec032e, #d78484);*/
  opacity: 0.95;
}
.common-layout {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  margin: 15px 100px 0 0;
  display: flex;
  padding-left: 48%;
}

.images-layout {
  width: 286px;
  height: 315px;
  background: url("../../assets/images/zhongyao2.png") no-repeat center/cover;
  position: absolute;
  margin-right: 70%;
  border-radius: 12px 1px 1px 12px ;
}

.el-input {
  width: 240px;
}
.check-code-panel {
  display: flex;
}

.password-login h1 {
  padding-top: 8px;
  padding-left: 50px;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #000000;
}
.qrcode-login h2 {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #000000;
}
.login {
  width: 100%;
  margin-top: 10px;
  border-radius: 10px;
}

.check-code-panel .el-input {
  width: 240px;
}
.login:not([disabled]):not(:active):hover {
  background-color: #18e752; /* 悬停时的背景色 */
  color: #dde33b; /* 悬停时的文字颜色 */
}

.login:active {
  background-color: #0ade27; /* 点击时的背景色 */
  color: #de0c0c; /* 点击时的文字颜色 */
}

#captchaImage {
  cursor: pointer;
  margin-left: 16px;
  border-radius: 5px;
  vertical-align: middle;
}

/* 调整验证码图片的悬停效果 */
#captchaImage:hover {
  opacity: 0.8;
  background-color: #abcedb;
}
.login:hover {
  background-color: #18e752;
  color: #dde33b;
}
.login:hover {
  background-color: #0ade27;
  color: #de0c0c;
}

.el-input:hover, .el-input:focus {
  border-color: #19d2a7;
  box-shadow: 0 0 10px rgba(28, 213, 102, 0.5);
}

</style>
